<template>
  <a-modal
    :visible="visible"
    title="添加文件"
    @ok="handleOk"
    @cancel="handleCancel"
    :ok-button-props="{ disabled: !selectedFile }"
  >
    <a-form layout="vertical">
      <a-form-item label="文件类型">
        <a-select v-model="fileType" disabled>
          <a-select-option :value="fileType">
            {{ getFileTypeLabel(fileType) }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="文件描述">
        <a-textarea v-model:value="fileDescription" placeholder="请输入文件描述" />
      </a-form-item>
      <a-form-item label="上传文件" required>
        <a-upload
          :before-upload="beforeUpload"
          :show-upload-list="true"
          :max-count="1"
          :accept="getAcceptType()"
          :file-list="fileList"
        >
          <a-button>
            <upload-outlined /> 选择文件
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { UploadOutlined } from '@ant-design/icons-vue';
import axios from  "axios"
export default {
  props: ['visible', 'currentType'],
  components: { UploadOutlined },
  data() {
    return {
      fileType: this.currentType || '',
      fileDescription: '',
      selectedFile: null,
      fileList: [],
      fileTypeOptions: [
        { value: 'ppt', label: 'PPT' },
        { value: 'transcript', label: '讲稿' },
        { value: 'plan', label: '教案' },
        { value: 'media', label: '媒体文件' }
      ],
      currentUser: 'user_' + Math.random().toString(36).substr(2, 9),
      difyConfig: {
        baseUrl: 'http://localhost/v1',
        apiKey: 'app-ijcvqqiPoXQs3RRyyYzLDOg1',
        endpoints: {
          chat: '/chat-messages'
        }
      },
    };
  },
  watch: {
    currentType(newVal) {
      this.fileType = newVal;
    },
    visible(newVal) {
      if (!newVal) {
      this.resetForm();
      }
    }
    },
  created(){
    this.fetchApiKeys();
  },
  methods: {
    async fetchApiKeys() {
      this.apiKeyLoading = true;
      try {
        const response = await axios.get('http://127.0.0.1:8000/api/knowledge-base-keys/');
        if (response.status === 200 && response.data) {
          const keys = response.data;
          this.difyConfig.apikey = keys.find(k => k.name === 'json数据转化助手')?.api_key || null;
        }
      } catch (error) {
        console.error('Failed to fetch API keys:', error);
      } finally {
        this.apiKeyLoading = false;
      }
    },
    getFileTypeLabel(type) {
      const option = this.fileTypeOptions.find(opt => opt.value === type);
      return option ? option.label : '';
    },
    getAcceptType() {
      switch(this.fileType) {
        case 'ppt':
          return '.ppt,.pptx';
        case 'transcript':
          return '.doc,.docx,.txt';
        case 'plan':
          return '.doc,.docx';
        case 'media':
          return '.mp4,.mov,.avi,.jpg,.jpeg,.png,.gif';
        default:
          return '*';
  }
    },
    beforeUpload(file) {
      const fileExt = file.name.split('.').pop().toLowerCase();
      const allowedExts = this.getAcceptType().replace(/\./g, '').split(',');

      if (!allowedExts.includes(fileExt)) {
        this.$message.error(`请选择${this.fileType}类型的文件`);
        return false;
      }
      this.selectedFile = file;
      this.fileList = [file];
      return false;
    },
    async handleOk() {
      if (!this.selectedFile) {
        this.$message.error('请选择文件');
        return;
      }
      
      try {
        // Close modal immediately
        this.$emit('update:visible', false);
        
        // Prepare basic file data
        const fileData = {
          file: this.selectedFile,
          type: this.fileType,
          name: this.selectedFile.name,
          content: this.fileDescription
        };

        // Emit event with all required data
        this.$emit('add-file', fileData);
        this.resetForm();
      } catch (error) {
        console.error('处理失败:', error);
        this.$message.error(`处理失败: ${error.message}`);
        this.$emit('update:visible', true); // Reopen modal on error
      }
    },
    async handleFileUpload(file) {
      try {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('user', this.currentUser);

        const response = await axios.post(
          `${this.difyConfig.baseUrl}/files/upload`,
          formData,
          {
            headers: {
              'Authorization': `Bearer ${this.difyConfig.apiKey}`,
              'Content-Type': 'multipart/form-data'
            }
          }
        );

        return response.data;
      } catch (error) {
        console.error('文件上传失败:', error);
        throw error;
      }
    },
    async handleAddNewFile(file) {
      try {
        if (!file?.name) {
          throw new Error('无效的文件对象');
        }

        // 1. Upload to Dify
        const uploadResult = await this.handleFileUpload(file);
        
        // 2. Get analysis
        const analysisResult = await this.sendAnalysisWithFileId(
          uploadResult.id, 
          file.name
        );
        
        // 3. Return clean analysis data
        return analysisResult || {};

      } catch (error) {
        console.error('文件分析失败:', error);
        throw new Error(`文件分析失败: ${error.message}`);
      }
    },

    async sendAnalysisWithFileId(fileId, filename) {
      const payload = {
        inputs: {},
        query: "请直接返回纯JSON格式的分析结果",
        response_mode: "blocking",
        user: this.currentUser,
        files: [{
          type: this.getDifyFileType(filename),
          transfer_method: "local_file",
          upload_file_id: fileId
        }]
      };

      try {
        const response = await axios.post(
          `${this.difyConfig.baseUrl}${this.difyConfig.endpoints.chat}`,
          payload,
          {
            headers: {
              'Authorization': `Bearer ${this.difyConfig.apiKey}`,
              'Content-Type': 'application/json'
            }
          }
        );

        let result = response.data?.answer || response.data;
        console.log('Raw API response:', result);
        
        if (typeof result === 'string') {
          try {
            // 更健壮的JSON清理逻辑
            const cleaned = result
              .replace(/^```(?:json)?\s*|\s*```$/g, '')  // 去除代码块标记
              .replace(/[\u0000-\u001F\u007F-\u009F]/g, '')  // 去除控制字符
              .replace(/"([^"]*)\n([^"]*)([^"}]*)$/gm, '"$1\\n$2$3"')  // 处理多行字符串
              .replace(/([}\]])[^}\]}]*$/, '$1');  // 确保JSON闭合

            return JSON.parse(cleaned);
          } catch (e) {
            console.error('JSON解析失败:', {
              error: e.message,
              response: result
            });
            throw new Error('分析结果格式异常，请检查API返回格式');
          }
        }
        return result;
      } catch (error) {
        console.error('分析请求失败:', error);
        throw error;
      }
    },
    handleCancel() {
      this.resetForm();
      this.$emit('update:visible', false);
    },
    getDifyFileType(filename) {
      const extension = filename.split('.').pop().toLowerCase();
      const typeMap = {
        doc: 'document',
        docx: 'document',
        pdf: 'document',
        jpg: 'image',
        png: 'image',
        mp3: 'audio',
        mp4: 'video'
      };
      return typeMap[extension] || 'file';
    },
    resetForm() {
      this.fileDescription = '';
      this.selectedFile = null;
      this.fileList = [];
    }
  }
};
</script>